#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include "RingQueue.hpp"

using namespace RingQueueMoudel;

void *Producer(void *args)
{
    RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    int data = 0;
    while(true)
    {
        // 1.获取数据

        // 2.生产数据
        rq->Push(data);
        std::cout << "producer 生产了一个数据" << data << std::endl;
        data++;
    }
}

void *Consumer(void *args)
{
    RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    while(true)
    {
        sleep(1);
        // 1.消费数据
        int data;
        rq->Pop(&data);

        // 2.处理数据
        std::cout << "consumer 消费了一个数据" << data << std::endl;
    }
}

int main1()
{
    RingQueue<int> *rq = new RingQueue<int>(5);

    pthread_t p, c;
    pthread_create(&p, nullptr, Producer, rq);
    pthread_create(&c, nullptr, Consumer, rq);

    pthread_join(p, nullptr);
    pthread_join(c, nullptr);

    // pthread_t p1, p2, c1, c2, c3;
    // pthread_create(&p1, nullptr, Producer, rq);
    // pthread_create(&p2, nullptr, Producer, rq);
    // pthread_create(&c1, nullptr, Consumer, rq);
    // pthread_create(&c2, nullptr, Consumer, rq);
    // pthread_create(&c3, nullptr, Consumer, rq);

    // pthread_join(p1, nullptr);
    // pthread_join(p2, nullptr);
    // pthread_join(c1, nullptr);
    // pthread_join(c2, nullptr);
    // pthread_join(c3, nullptr);

    delete rq;

    return 0;
}

#include <iostream>
#include <unistd.h>
#include <semaphore.h>
#include "Mutex.hpp"

int ticket = 1000;
sem_t sem;
Mutex mutex;

void* Ticket(void *args)
{
    std::string name = static_cast<char*>(args);
    while(true)
    {
        sem_wait(&sem); // 申请信号量
        LockGuard lockguard(mutex); // RAII方式加锁

        if(ticket > 0)
        {
            usleep(1000);
            std::cout << name << " buys a ticket: " << ticket << std::endl;
            ticket--;
            sem_post(&sem);  // 释放信号量
        }
        else
        {
            sem_post(&sem); // 释放信号量
            break;
        }
    }
    return nullptr;
}

int main()
{
    sem_init(&sem, 0, 3); // 允许最多3个线程访问共享资源

    pthread_t t1, t2, t3;
    pthread_create(&t1, nullptr, Ticket, (void*)"thread-1");
    pthread_create(&t2, nullptr, Ticket, (void*)"thread-2");
    pthread_create(&t3, nullptr, Ticket, (void*)"thread-3");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    sem_destroy(&sem);

    return 0;
}